package com.zhangmeng.tools.controller;

import com.zhangmeng.tools.utils.AlertUtils;
import com.zhangmeng.tools.utils.ImagePath;
import com.zhangmeng.tools.utils.PlateUtil;
import javafx.application.Platform;
import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-04-01 10:46
 */
@Slf4j
public class PdfOcrController {

    public static String tessdata = System.getProperty("user.dir");

    @FXML
    public Button file_choose_button;

    @FXML
    public TextArea res_view;

    @FXML
    public Button cover;

    @FXML
    public TextField file_path;

    public static final SimpleObjectProperty<File> choose_file = new SimpleObjectProperty<>();

    @FXML
    public void initialize() {

        file_choose_button.setText(null);
        ImageView iv = new ImageView(new Image(ImagePath.path(ImagePath.ImagePathType.IMAGE_FILE)));
        iv.setPreserveRatio(true);
        iv.setFitWidth(18);
        file_choose_button.setGraphic(iv);

        cover.setText("识别");

        file_choose_button.setOnAction(event -> {
            choose_file();
        });

        cover.setOnAction(event -> {
            if (choose_file.getValue() == null) {
                AlertUtils.alert_warning("请选择将要识别的pdf再试!");
                return;
            }

            File file = choose_file.getValue();
            Stage alert = AlertUtils.alert_loading(cover.getScene().getWindow());
            new Thread(() -> {
                Platform.runLater(() -> {
                    init_pdf(file);
                    alert.close();
                });
            }).start();
        });
    }

    public void choose_file() {
        Stage stage = new Stage();
        FileChooser dc = new FileChooser();
        dc.setTitle("文件选择");
        dc.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("类型", "*.pdf"));
        File file = dc.showOpenDialog(stage);
        if (file != null) {
            String path = file.getAbsolutePath();
            file_path.setText(path);
            log.info("file_path:{}", path);
            choose_file.set(file);
        }
    }

    public void init_pdf(File file) {
        String result = PlateUtil.getPdfContent(file);
        res_view.setText(result);
    }
}
